import requests
from rest_framework.decorators import api_view
from rest_framework.response import Response

from xuanba_model.models import FoodTags, Eatery


@api_view(['GET'])
def classify(request):
    tags = FoodTags.objects.all()
    alls = []
    for tag in tags:
        name = tag.tag_name
        alls.append(name)
    result = {'code': 200, 'result': 'success', 'data': alls[:8]}
    return Response(result)


@api_view(['GET'])
def eatery_list(request, tag, area):
    if area == '成都':
        shops = Eatery.objects.filter(eatery_name__contains=tag)
    else:
        shops = Eatery.objects.filter(eatery_name__contains=tag, address__contains=area)
    alls = []
    i = 0
    for shop in shops:
        shop_dict = {}
        props = ['eatery_id', 'eatery_name', 'score', 'avg_cost', 'tel',
                 'address', 'picture', 'is_wifi', 'longitude', 'latitude']
        for prop in props:
            value = getattr(shop, prop, '')
            shop_dict[prop] = value
        alls.append(shop_dict)
    result = {'code': 200, 'result': 'success', 'data': alls[:20]}
    return Response(result)

@api_view(['GET'])
def eatery_detail(request, id):
    shop = Eatery.objects.filter(eatery_id=id).first()
    shop_dict = {}
    props = ['eatery_id', 'eatery_name', 'score', 'avg_cost', 'tel',
             'address', 'picture', 'is_wifi', 'longitude', 'latitude']
    for prop in props:
        value = getattr(shop, prop, '')
        shop_dict[prop] = value
    result = {'code': 200,'result': 'success', 'data': shop_dict}
    return Response(result)

# @api_view(['GET'])
# def ss(request, tag, area):
#     url = 'http://api.map.baidu.com/place/v2/search?query="火锅"&region="成都"&output=json&ak=1TGFhN58H5TOZfi7oQCNM9zSIwlb14hP'
#     res = requests.get(url)
#     info = json.loads(res.text)
#     names = []
#     result = []
#     for item in info['results']:
#         # if '(' in item['name']:
#         #     print(item['name'])
#         #     print(type(item['name']))
#         #     a = item['name'].replace('(', '（')
#         #     b = a.replace(')', '）')
#         #     names.append(b)
#         # else:
#         names.append(item['name'])
#     for name in names:
#         quer = TbShop.objects.filter(name=name).first()
#         if quer is not None:
#             shop_dict = {}
#             shop_dict['name'] = quer.name
#             shop_dict['score'] = quer.score
#             shop_dict['picture'] = quer.picture
#             shop_dict['adress'] = quer.adress
#             shop_dict['price'] = quer.price
#             result.append(shop_dict)
#
#     return Response(result)

# queryset = TbShop.objects.filter(name__in=(x for x in names()))






